/*
 * @(#)MessageHandler.java 	1.0 2010/07/29
 *
 * Copyright 2010 guyven and David Croft. All rights reserved.
 */
package com.iawg.attrition.engine.messaging;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Handles {@link BasicMessagePrefix}s received by the active elements of the game,
 * producing effects that can be rendered by the engine.
 * 
 * @author guyven
 * @version 1.0 2010/07/29
 */
public class MessageHandler <P extends Enum<P> & MessagePrefix<M>, M extends Message<P,M>> {
	/** A log of all messages that have been placed into the queue. */
	List<M> log = new ArrayList<M>();
	/** The queue of messages to be processed */
	BlockingQueue<M> unHandled = new ArrayBlockingQueue<M>(40);
	
	/**
	 * Notifies the Engine that something has happened, will block if there is no
	 * room in the queue (until there is).
	 * 
	 * @param message The message to place into the queue.
	 * @throws InterruptedException if something happened while waiting to add this to the queue.
	 */
	public void inform(M message) throws InterruptedException{
		log.add(message);
		unHandled.put(message);
	}
	
	/**
	 * Notifies the Engine that something has happened, will block if there is no
	 * room in the queue (until there is).
	 * 
	 * @param messagePrefix The message header.
	 * @param body The pay load of the message.
	 * @throws InterruptedException if something happened while waiting to add this to the queue.
	 */
	public void inform(P messagePrefix, Object body) throws InterruptedException{
		inform(messagePrefix.makeMessage(body));
	}

	/**
	 * Gets the messages being sent to the engine.  Will block until a
	 * message is available if none are.
	 * 
	 * @return the oldest unhandled message in this handler
	 * @throws InterruptedException if something happened while waiting to get another Message
	 */
	public M getNextMessage() throws InterruptedException {
		M message = unHandled.take();
		System.out.println("Message Handled: '" + message.prefix + "'");
		return message;
	}
}